package com.boot.springboot.component.qlexpress.service;

import com.boot.springboot.component.qlexpress.domain.UserInfo;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author luowenjie
 * @since 2022/2/12 16:03
 */
public class QlService {

    ExpressRunner runner = new ExpressRunner();

    /**
     * 判断用户 tag 是否为 tagBitIndex
     * @param user
     * @param tagBitIndex
     * @return
     */
    public boolean userTagJudge(UserInfo user, int tagBitIndex){
        boolean r =  user.getUserTag() == tagBitIndex;
        return r;
    }

    /**
     * 判断用户id 是否为 storeId
     * @param user
     * @param storeId
     * @return
     */
    public boolean hasOrderGoods(UserInfo user,long storeId){
        //随机模拟一个
        if(user.getUserId() ==storeId){
            return true;
        }else{
            return false;
        }
    }

    public void initial() throws Exception{
        runner.addOperatorWithAlias("而且","and",null);
        runner.addOperatorWithAlias("或者","or",null);
        runner.addFunctionOfClassMethod("userTagJudge", QlService.class.getName(), "userTagJudge",
                new String[] {UserInfo.class.getName(),"int"}, "你不是三星卖家");
        runner.addFunctionOfClassMethod("hasOrderGoods", QlService.class.getName(), "hasOrderGoods",
                new String[] {UserInfo.class.getName(),"long"}, "你没有开通淘宝店铺");
        runner.addMacro("三星卖家", "userTagJudge(userInfo,3)");//3表示三星卖家的标志位
        runner.addMacro("已经开店", "hasOrderGoods(userInfo,100)");//100表示旺铺商品的ID
    }

    /**
     * 判断逻辑执行函数
     * @param userInfo
     * @param expression
     * @return
     * @throws Exception
     */
    public String hasPermission(UserInfo userInfo,String expression) throws Exception {
        IExpressContext<String,Object> expressContext = new DefaultContext<String,Object>();
        expressContext.put("userInfo",userInfo);
        List<String> errorInfo = new ArrayList<String>();
        Boolean result = (Boolean)runner.execute(expression, expressContext, errorInfo, true, false);
        String resultStr ="";
        if(result.booleanValue() == true){
            resultStr = "可以订购此商品";
        }else{
            for(int i=0;i<errorInfo.size();i++){
                if(i > 0){
                    resultStr  = resultStr + "," ;
                }
                resultStr  = resultStr + errorInfo.get(i);
            }
            resultStr = resultStr  + ",所以不能订购此商品";
        }
        return "亲爱的" + userInfo.getName() + " : " + resultStr;
    }

}
